package git.soulbgm.controller;

import git.soulbgm.common.base.BaseController;
import git.soulbgm.common.pojo.Response;
import git.soulbgm.common.enums.CodeEnum;
import git.soulbgm.service.LoginService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

import static git.soulbgm.common.MonitorConstants.*;

/**
 * 登录控制器
 *
 * @author SoulBGM
 * @date 2022/03/22 17:03
 */
@RestController
public class LoginController extends BaseController {

    private final LoginService loginService;

    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    @PostMapping("login")
    public Response login(String username, String password, HttpSession session) {
        boolean result = loginService.login(username, password);
        if (result) {
            //登录成功，session中加入登录用户名，用于在成功的首页中展示
            session.setAttribute("username", username);
            return success(CodeEnum.LOGIN_SUCCESS);
        } else {
            return error(CodeEnum.LOGIN_FAIL);
        }
    }

    @PostMapping(URI_UNLOCK_SCREEN)
    public Response unlockScreen(String password, HttpSession session) {
        String username = (String) session.getAttribute("username");
        boolean result = loginService.login(username, password);
        if (result) {
            //解锁屏幕成功，session中删除lock标识
            session.removeAttribute(SESSION_LOCK);
            return success();
        } else {
            return error("密码错误");
        }
    }

}
